/*
 * Copyright (c) 2010-2012 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */

#include "xparameters.h"
#include "xil_cache.h"
#include "widget.h"
#include "regs.h"
#include "platform_config.h"
#include "xintc.h"
#include "xuartlite.h"
#include "xuartlite_l.h"
#include "xil_exception.h"

extern UIState uistate;

XUartLite UART;

void (*RecvCallback)(void);

void intr_hdlr(void *InstancePtr) {
    uistate.keyentered = rKEY_VALUE;
}

volatile u8 read_ch;

void recv_hdlr(void) {
	XUartLite_DisableIntr(XPAR_AXI_UARTLITE_0_BASEADDR);
	while(!XUartLite_IsReceiveEmpty(XPAR_AXI_UARTLITE_0_BASEADDR)) {
		read_ch = (u8)XUartLite_ReadReg(XPAR_AXI_UARTLITE_0_BASEADDR,XUL_RX_FIFO_OFFSET);
		XUartLite_SendByte(XPAR_AXI_UARTLITE_0_BASEADDR,read_ch);
	}
	XUartLite_EnableIntr(XPAR_AXI_UARTLITE_0_BASEADDR);
}

void RecvDone(void)
{
	int nI;
	xil_printf("uuuuu\n\r");
}

void cleanup_platform() {
    disable_caches();
}

void enable_caches() {
    Xil_ICacheEnable();
}

void disable_caches() {
    Xil_DCacheDisable();
    Xil_ICacheDisable();
}

void init_platform() {

	static XIntc intc;

    enable_caches();
    XUartLite_Initialize(&UART, XPAR_AXI_UARTLITE_0_DEVICE_ID) ;
    XUartLite_ResetFifos(&UART);
    XUartLite_EnableInterrupt(&UART);

    RecvCallback = RecvDone;

    xil_printf("******************stag0 cpu init***********************************\n\r");
    XIntc_Initialize(&intc, XPAR_AXI_INTC_0_DEVICE_ID);
    XIntc_Connect(&intc, XPAR_AXI_INTC_0_SYSTEM_TP_INTR_0_INTR, (XInterruptHandler) intr_hdlr, (void *) 0 );
    XIntc_Enable(&intc, XPAR_AXI_INTC_0_SYSTEM_TP_INTR_0_INTR);

    XIntc_Connect(&intc, XPAR_AXI_INTC_0_AXI_UARTLITE_0_INTERRUPT_INTR, (XInterruptHandler) recv_hdlr, (void *) 0 );
    XIntc_Enable(&intc, XPAR_AXI_INTC_0_AXI_UARTLITE_0_INTERRUPT_INTR);

    XIntc_Start(&intc, XIN_REAL_MODE);
    microblaze_enable_interrupts();

}

